export default  class AudioPlayer {
  constructor() {
    this.options = {
      times: 2,
      sleep: 5000,
      ... arguments[0]
    }

    this.audio = new Audio();
    this.queue = [];       // 存储音频元素的队列
    this.isProcessing = false; // 标记是否正在处理队列
    this.sleep = 2000;

    // 监听播放结束事件
    this.audio.addEventListener('ended', () => {
      // 结束后等待n秒再处理下一个
      setTimeout(() => {
        this._next();
      }, this.sleep);
    });

    // 处理播放错误，避免队列中断
    this.audio.addEventListener('error',  err => {
      console.error(err,'播放失败，继续下一曲目');
      this._next(); // 立即尝试播放下一个
    });
  }

  // 设置配置
  setOptions(options){
    this.options = {
      ... this.options,
      ... options
    }
  }

  // 添加音频到队列
  setQueue(queue) {
    this.queue = [];
    queue.forEach(item => {
      let playbackRate = 1;
      let sleep = 1500;
      for(let i = 0; i < this.options.times; i++){
        if(i == this.options.times - 1){
          sleep = this.options.sleep;
        }
        this.queue.push({
          src: item,
          sleep: sleep,
          playbackRate: playbackRate
        });
        playbackRate = 0.8;
        sleep = 1500;
      }

    })

  }

  play(){
    return new Promise(resolve => {
      console.log('休眠'+ this.sleep)
      setTimeout(() => {
        this._next();
      }, this.sleep)
      let interval = setInterval(() => {
        if(this.queue.length == 0 && !this.isProcessing){
          resolve()
          clearInterval(interval);
        }
      }, 200)

    })

  }

  //
  _next() {
    if (this.queue.length === 0) {
      this.isProcessing = false;
      return;
    }
    this.isProcessing = true;
    let item = this.queue.shift(); // 取出队列中的第一个音频
    this.sleep = item.sleep;

    this.audio.src = item.src;
    //this.audio.volume = 1
    console.log(item.src);
    console.log('休眠'+ this.sleep)
    this.audio.playbackRate = item.playbackRate;
    // 播放音频
    this.audio.play();
  }
}

